﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace cscope_trim
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length < 1)
                return;

            if (!File.Exists(args[0]))
                return;

            string ifile = args[0];
            string ofile = ifile + ".tmp";
            StreamReader sr = new StreamReader(ifile, Encoding.GetEncoding("big5"));
            StreamWriter sw = new StreamWriter(ofile, false, Encoding.GetEncoding("big5"));
            sw.NewLine = "\n";
            string line;
            bool skip = false;
            List<string> flist = new List<string>();
            string fname;

            while ((line = sr.ReadLine()) != null)
            {
                if (line.StartsWith("\t@"))
                {
                    if (line.EndsWith("@"))
                    {
                        sw.WriteLine(line);
                        break;
                    }

                    //line = line.ToLower();
                    fname = line.Substring(2);
                    if (flist.Contains(fname, StringComparer.OrdinalIgnoreCase))
                    {
                        skip = true;
                    }
                    else
                    {
                        flist.Add(fname);
                        skip = false;
                    }
                }
                
                if (!skip)
                    sw.WriteLine(line);
            }

            //while ((line = sr.ReadLine()) != null)
            //{
            //    sw.WriteLine(line);
            //}
            sw.Flush();
            long tailOffset = sw.BaseStream.Position;
            sw.WriteLine("1");
            sw.WriteLine(".");
            sw.WriteLine("0");
            sw.WriteLine(flist.Count);
            int sz = 0;
            foreach (string s in flist)
            {
                sz += s.Length + 1;
            }
            sw.WriteLine(sz);
            foreach (string s in flist)
            {
                sw.WriteLine(s);
            }
            sr.Close();
            sw.Flush();
            sw.Close();


            StreamReader sr2 = new StreamReader(ofile, Encoding.GetEncoding("big5"));
            StreamWriter sw2 = new StreamWriter(ifile+".trim", false, Encoding.GetEncoding("big5"));
            sw2.NewLine = "\n";

            line = sr2.ReadLine();
            line = line.Substring(0, line.Length - 10) + tailOffset.ToString("D10");
            sw2.WriteLine(line);
            while ((line = sr2.ReadLine()) != null)
                sw2.WriteLine(line);

            sr2.Close();
            sw2.Close();
            File.Delete(ofile);
        }
    }
}
